﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Security.Cryptography;


namespace Talk
{
    public partial class vote : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Regex r = new Regex("[^0-9]");
            if(Session["UserID"]==null || Request.QueryString["a"]==null
                || Request.QueryString["i"]==null || r.IsMatch(Request.QueryString["i"].ToString()))
            {
                Response.Redirect("/index.aspx");
                return;
            }
            string act;
            string id=Request.QueryString["i"].ToString();
            if (Request.QueryString["a"].ToString() == "pro") act = "nPro";
            else if (Request.QueryString["a"].ToString() == "con") act = "nCon";
            else
            {
                Response.Redirect("/index.aspx");
                return;
            }
            try
            {
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["talkconn"].ConnectionString);
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.CommandText = "insert into Votes values('"
                    + Session["UserID"].ToString() + "', '"
                    + id + "')";
                if(cmd.ExecuteNonQuery()>0)
                {
                    cmd.CommandText = "update Messages set "
                        + act + " = " + act + " + 1 where MessageID = '"
                        + id + "'";
                    cmd.ExecuteNonQuery();
                }
                cmd.CommandText = "insert into Actions(UserID,What,Time,IP) values("
                   + Session["UserID"].ToString()
                   + ",'" + Session["Username"] + (act == "nPro"?"支持":"反对") + "文章"+ id.ToString()+ "','"
                   + DateTime.Now.ToString() + "','"
                   + Request.UserHostAddress.ToString()
                   + "');";
                cmd.ExecuteNonQuery();

                conn.Close();
                Response.Redirect("/index.aspx", false);
                return;
            }
            catch (System.Exception ex)
            {
                Response.Redirect("/index.aspx?" + "err=" + ex.Message.Replace('\n', '.'));
            }
        }
    }
}
